package com.zh.config.utils

import com.zh.common.utils.EmptyUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.HttpURLConnection
import java.net.URL
import java.util.Locale

/**
 * 判断下来链接
 */
object LinkCheckIsDown {

    fun isDownloadLinkWithMimeType(url: String?, call: (Boolean) -> Unit) {
        val mainScope = MainScope()
        try {
            mainScope.launch(Dispatchers.IO) {
                val u = URL(url)
                val connection = u.openConnection() as HttpURLConnection
                connection.requestMethod = "HEAD" // 发送 HEAD 请求
                // 获取 MIME 类型
                val contentType = connection.contentType
                // 关闭连接
                connection.disconnect()
                mainScope.cancel()
                // 检查 MIME 类型
                withContext(Dispatchers.Main) {
                    call.invoke(isDownloadMimeType(contentType))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            mainScope.cancel()
            call.invoke(false) // 在发生异常时默认不认为是下载链接
        }
    }

    private fun isDownloadMimeType(mimeType: String): Boolean {
        // 定义常见的可下载 MIME 类型
        val commonDownloadMIMETypes = arrayOf(
            "application/pdf",
            "application/zip",
            "application/x-zip-compressed",
            "application/octet-stream",
            "application/msword",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "image/jpeg",
            "image/png",
            "audio/mpeg",
            "audio/wav"
        )
        for (type in commonDownloadMIMETypes) {
            if (mimeType.startsWith(type)) {
                return true
            }
        }
        return false
    }

    fun isDownloadLink(url: String): Boolean {
        if (EmptyUtils.isEmpty(url)) {
            return false
        }
        // 提取 URL 的文件扩展名
        val extension = getFileExtension(url)
        // 定义常见的下载文件扩展名
        val commonExtensions = arrayOf(
            ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
            ".txt", ".zip", ".rar", ".tar", ".gz", ".7z", ".mp3", ".wav",
            ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".apk", ".mp4"
        )
        for (ext in commonExtensions) {
            if (extension.equals(ext, ignoreCase = true)) {
                return true
            }
        }
        // 如果没有匹配的扩展名，则默认不认为是下载链接
        return false
    }

    private fun getFileExtension(url: String): String {
        val lastDotIndex = url.lastIndexOf('.')
        return if (lastDotIndex == -1) {
            ""
        } else {
            url.substring(lastDotIndex).split("?")[0].lowercase(Locale.getDefault())
        }
    }
}